package com.lj.listener;

import com.lj.dao.SqliteHelper;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created by dave_suwei on 2017/12/9.
 */
public class MyServletRequestListener implements ServletRequestListener {
    public void requestDestroyed(ServletRequestEvent sre) {
        SqliteHelper sqliteHelper= (SqliteHelper) sre.getServletRequest().getAttribute("sh");
        if(sqliteHelper!=null){
            sqliteHelper.destroyed();
            System.out.println("sqliteHelper.destroyed()");
        }
        sre.getServletRequest().removeAttribute("sh");
    }

    public void requestInitialized(ServletRequestEvent sre) {
        Properties properties=new Properties();
        String dbPath=null;
        try {
            properties.load(getClass().getResourceAsStream("/application.properties"));
            dbPath=properties.getProperty("database.path");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(dbPath==null){
            dbPath=sre.getServletContext().getRealPath("/")+"unburden.db";
        }
        System.out.println("dbPath->"+dbPath);
        try {
            SqliteHelper sqliteHelper=new SqliteHelper(dbPath);
            sre.getServletRequest().setAttribute("sh",sqliteHelper);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
